# -*- coding: utf-8 -*-

"""
@author: 猿小天

@contact: QQ:1638245306

@Created on: 2020/9/7 007 22:01

用于websocket的配置
"""
import json
import urllib
CONNECTIONS=[]

#处理websocket传参
def request_data(scope):
    query_string = scope.get('query_string', b'').decode('utf-8')
    qs = urllib.parse.parse_qs(query_string)
    return qs


async def websocket_application(scope, receive, send):
    while True:
        event = await receive()
        #收到建立websocket连接的消息
        if event['type'] == 'websocket.connect':
            await send({'type': 'websocket.accept'})
            res = request_data(scope)
            userId = res.get('userId')[0]
            print("userId",userId)
            # res = json.dumps(res)
            CONNECTIONS.append({
                "userId": userId,
                "send": send
            })
            datas = {'type': 'websocket.send', 'text': '您已连接成功'}
            await send(datas)
        #收到中断websocket连接的消息
        elif event['type'] =='websocket.disconnect':
            break
        # 其他情况,正常的websocket消息
        elif event['type'] == 'websocket.receive':
            #print("[event]", event)
            # print("[scope]", scope)
            res = request_data(scope)
            userId = res.get('userId')[0]
            target = json.loads(event['text'])
            targetuser = target.get('to',None)
            print('targetuser',targetuser)
            datas = {'type': 'websocket.send', 'text': "{0}".format(target.get('content',''))}
            #print(CONNECTIONS)
            for con in CONNECTIONS:
                if targetuser is None:
                    if con['userId'] != userId:
                        await con['send'](datas)
                else:
                    if con['userId'] == targetuser:
                        await con['send'](datas)
            await send({'type': 'websocket.send', 'text': "{0}".format(target.get('content',''))})
        else:
            print("[event]",event)
            pass
    print("[disconnect]")